<script setup lang="ts">
// import { postArticle, updateArticle } from '@/api/article';
import { hideLoading, showErrorToast, showLoading, showSuccessToast, showToast } from '@/utils/feedback';
import { ref } from 'vue';

// 表单数据
const formData = ref({
  id: '', // 编辑时传入
  title: '',
  content: '',
  category: '',
  tags: [] as string[],
  cover: '',
  status: 'draft' as 'draft' | 'published',
});

// 分类选项
const categories = ref([
  { value: 'technology', label: '技术' },
  { value: 'life', label: '生活' },
  { value: 'travel', label: '旅行' },
  { value: 'reading', label: '阅读' },
]);

// 标签输入
const tagInput = ref('');
const isAddingTag = ref(false);

// 添加标签
function addTag() {
  if (tagInput.value.trim() && !formData.value.tags.includes(tagInput.value.trim())) {
    formData.value.tags.push(tagInput.value.trim());
    tagInput.value = '';
  }
  isAddingTag.value = false;
}

// 移除标签
function removeTag(index: number) {
  formData.value.tags.splice(index, 1);
}

// 选择封面
async function chooseCover() {
  try {
    const res = await uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album'],
    });
    formData.value.cover = res.tempFilePaths[0];

    // 这里可以添加图片上传逻辑
    showLoading('上传封面中...');
    // const uploadRes = await uploadFile(res.tempFilePaths[0])
    // formData.value.cover = uploadRes.url
    hideLoading();
  } catch (error) {
    console.error('选择图片失败:', error);
    showToast('封面选择失败', 'error');
  }
}

// 保存为草稿
async function saveAsDraft() {
  if (!formData.value.title.trim()) {
    showToast('请输入文章标题');
    return;
  }

  showLoading('保存中...');
  formData.value.status = 'draft';

  try {
    // const apiMethod = formData.value.id ? updateArticle : postArticle;
    // const res = await apiMethod(formData.value);
    const res = {};
    // 如果是新建文章，设置返回的ID
    if (!formData.value.id && res.data?.id) {
      formData.value.id = res.data.id;
    }

    hideLoading();
    showSuccessToast('草稿保存成功');
  } catch (error) {
    hideLoading();
    console.error('保存草稿失败:', error);
    showErrorToast('草稿保存失败，请重试');
  }
}

// 发布文章
async function publishArticle() {
  if (!formData.value.title.trim()) {
    showToast('请输入文章标题');
    return;
  }

  if (!formData.value.content.trim()) {
    showToast('请输入文章内容');
    return;
  }

  if (!formData.value.category) {
    showToast('请选择文章分类');
    return;
  }

  showLoading('发布中...');
  formData.value.status = 'published';

  try {
    // const apiMethod = formData.value.id ? updateArticle : postArticle;
    // await apiMethod(formData.value);

    hideLoading();
    showSuccessToast('文章发布成功');
    // router.push({ path: '/pages/article/list' });
  } catch (error) {
    hideLoading();
    console.error('发布失败:', error);
    showErrorToast('文章发布失败，请重试');
  }
}
</script>

<template>
  <view class="min-h-screen bg-gray-50 pb-20">
    <!-- 主要内容区 -->
    <view class="px-4 pt-4">
      <!-- 标题输入 -->
      <view class="mb-6">
        <input
          v-model="formData.title"
          placeholder="请输入标题..."
          class="w-full text-2xl font-bold border-b border-gray-200 pb-2 focus:border-blue-500 focus:outline-none"
          maxlength="100"
        >
      </view>

      <!-- 封面图片 -->
      <view class="mb-6">
        <text class="block text-sm font-medium text-gray-700 mb-2">
          封面图片
        </text>
        <view
          class="relative w-full h-40 bg-gray-100 rounded-lg overflow-hidden flex items-center justify-center"
          @click="chooseCover"
        >
          <template v-if="formData.cover">
            <image :src="formData.cover" class="w-full h-full object-cover" mode="aspectFill" />
            <view class="absolute inset-0 bg-black bg-opacity-20 flex items-center justify-center">
              <uni-icons type="camera-filled" size="32" color="#fff" />
            </view>
          </template>
          <template v-else>
            <uni-icons type="plus" size="32" color="#9CA3AF" />
            <text class="text-gray-400 ml-2">
              添加封面
            </text>
          </template>
        </view>
      </view>

      <!-- 分类选择 -->
      <view class="mb-6">
        <text class="block text-sm font-medium text-gray-700 mb-2">
          分类
        </text>
        <picker
          :value="formData.category"
          :range="categories"
          range-key="label"
          class="border border-gray-200 rounded-lg px-4 py-2"
        >
          <view class="flex justify-between items-center">
            <text class="text-gray-800">
              {{ formData.category ? categories.find(c => c.value === formData.category)?.label : '请选择分类' }}
            </text>
            <uni-icons type="arrowdown" size="16" color="#666" />
          </view>
        </picker>
      </view>

      <!-- 标签管理 -->
      <view class="mb-6">
        <text class="block text-sm font-medium text-gray-700 mb-2">
          标签
        </text>
        <view class="flex flex-wrap gap-2 mb-2">
          <view
            v-for="(tag, index) in formData.tags"
            :key="index"
            class="inline-flex items-center bg-blue-100 text-blue-800 rounded-full px-3 py-1 text-sm"
          >
            {{ tag }}
            <uni-icons
              type="close"
              size="14"
              color="#1E40AF"
              class="ml-1 cursor-pointer"
              @click="removeTag(index)"
            />
          </view>
        </view>

        <view v-if="!isAddingTag" class="flex">
          <button
            class="flex items-center text-blue-600 text-sm"
            @click="isAddingTag = true"
          >
            <uni-icons type="plus" size="16" color="#2563EB" class="mr-1" />
            添加标签
          </button>
        </view>

        <view v-else class="flex items-center">
          <input
            v-model="tagInput"
            placeholder="输入标签"
            class="flex-1 border border-gray-200 rounded-l-lg px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
            @confirm="addTag"
          >
          <button
            class="bg-blue-500 text-white px-3 py-2 rounded-r-lg text-sm"
            @click="addTag"
          >
            添加
          </button>
        </view>
      </view>

      <!-- 富文本编辑器 -->
      <view class="mb-6">
        <text class="block text-sm font-medium text-gray-700 mb-2">
          正文
        </text>
        <editor
          id="editor"
          class="border border-gray-200 rounded-lg p-3 min-h-[400px] bg-white"
          placeholder="开始创作..."
          show-img-size
          show-img-toolbar
          show-img-resize
          @input="(e) => formData.content = e.detail.html"
        />
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 flex justify-between">
      <button
        class="flex-1 bg-gray-100 text-gray-800 py-2 rounded-lg mr-2 font-medium flex items-center justify-center"
        @click="saveAsDraft"
      >
        <uni-icons type="plus" size="16" color="#4B5563" class="mr-1" />
        暂存草稿
      </button>
      <button
        class="flex-1 bg-blue-500 text-white py-2 rounded-lg font-medium flex items-center justify-center"
        @click="publishArticle"
      >
        <uni-icons type="paperplane" size="16" color="#fff" class="mr-1" />
        发布文章
      </button>
    </view>
  </view>
</template>

<style>
/* 自定义编辑器样式 */
#editor {
  font-size: 16px;
  line-height: 1.6;
}

/* 适配小程序的一些样式调整 */
button::after {
  border: none;
}
</style>
